package com.example.blogback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blogback.dto.CategoryDTO;
import com.example.blogback.entity.Article;
import com.example.blogback.entity.Category;
import com.example.blogback.mapper.ArticleMapper;
import com.example.blogback.mapper.CategoryMapper;
import com.example.blogback.service.CategoryService;
import com.example.blogback.vo.CategoryTreeVO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private ArticleMapper articleMapper;

    @Override
    @Transactional
    public void createCategory(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        
        // 设置分类层级
        category.setLevel(categoryDTO.getParentId() == null ? 1 : 2);
        save(category);
    }

    @Override
    @Transactional
    public void updateCategory(CategoryDTO categoryDTO) {
        Category category = getById(categoryDTO.getId());
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }
        BeanUtils.copyProperties(categoryDTO, category);
        updateById(category);
    }

    @Override
    @Transactional
    public void deleteCategory(Long id) {
        Category category = getById(id);
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }
        // 删除分类及其子分类
        removeById(id);
        if (category.getLevel() == 1) {
            remove(new LambdaQueryWrapper<Category>().eq(Category::getParentId, id));
        }
    }

    @Override
    public List<Category> getCategoryTree() {
        List<Category> allCategories = list();
        
        // 按父ID分组
        Map<Long, List<Category>> categoryMap = allCategories.stream()
                .collect(Collectors.groupingBy(category -> 
                    category.getParentId() == null ? 0L : category.getParentId()));
        
        // 获取一级分类
        List<Category> topCategories = categoryMap.getOrDefault(0L, new ArrayList<>());
        
        // 为一级分类设置子分类
        topCategories.forEach(category -> {
            List<Category> children = categoryMap.getOrDefault(category.getId(), new ArrayList<>());
            children.sort((a, b) -> (a.getSort() == null ? 0 : a.getSort()) - 
                    (b.getSort() == null ? 0 : b.getSort()));
            category.setChildren(children);
        });
        
        // 按排序字段排序
        topCategories.sort((a, b) -> (a.getSort() == null ? 0 : a.getSort()) - 
                (b.getSort() == null ? 0 : b.getSort()));
        
        return topCategories;
    }

    @Override
    public List<Category> getTopCategories() {
        return list(new LambdaQueryWrapper<Category>()
                .isNull(Category::getParentId)
                .orderByAsc(Category::getSort));
    }

    @Override
    public List<Category> getSubCategories(Long parentId) {
        return list(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, parentId)
                .orderByAsc(Category::getSort));
    }

    @Override
    public CategoryTreeVO getCategoryTreeWithArticles(Long categoryId) {
        // 获取一级分类
        Category parentCategory = getById(categoryId);
        if (parentCategory == null) {
            throw new RuntimeException("分类不存在");
        }

        CategoryTreeVO treeVO = new CategoryTreeVO();
        treeVO.setId(parentCategory.getId());
        treeVO.setName(parentCategory.getName());
        treeVO.setDescription(parentCategory.getDescription());

        // 获取二级分类
        List<Category> subCategories = list(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, categoryId));

        List<CategoryTreeVO.SubCategoryVO> children = new ArrayList<>();
        for (Category subCategory : subCategories) {
            CategoryTreeVO.SubCategoryVO subVO = new CategoryTreeVO.SubCategoryVO();
            subVO.setId(subCategory.getId());
            subVO.setName(subCategory.getName());
            subVO.setDescription(subCategory.getDescription());

            // 获取该二级分类下的文章
            List<Article> articles = articleMapper.selectList(new LambdaQueryWrapper<Article>()
                    .eq(Article::getCategoryId, subCategory.getId())
                    .orderByDesc(Article::getCreateTime));
            subVO.setArticles(articles);

            children.add(subVO);
        }

        treeVO.setChildren(children);
        return treeVO;
    }
}